# data_storage/export_data.py - Data export functionality

import os
import csv
import json
import logging

logger = logging.getLogger(__name__)


def export_to_json(events, output_file):
    """
    Export events to a JSON file

    Args:
        events: List of event dictionaries
        output_file: Path to the output JSON file

    Returns:
        True if successful, False otherwise
    """
    try:
        # Create output directory if it doesn't exist
        os.makedirs(os.path.dirname(output_file), exist_ok=True)

        # Process events for export
        export_data = []

        for event in events:
            # Create a clean copy of the event for export
            export_event = {
                'id': event.get('id'),
                'type': event.get('type', ''),
                'start_time': event.get('start_time', 0),
                'end_time': event.get('end_time', 0),
                'duration': event.get('duration', 0),
                'confidence': event.get('confidence', 0),
                'video_path': event.get('video_path', ''),
                'output_file': event.get('output_file', '')
            }

            # Add frames if available
            if 'frames' in event:
                export_event['frame_start'] = event['frames'].get('start', 0)
                export_event['frame_end'] = event['frames'].get('end', 0)

            export_data.append(export_event)

        # Write to JSON file
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(export_data, f, indent=2)

        logger.info(f"Exported {len(events)} events to {output_file}")
        return True

    except Exception as e:
        logger.error(f"Error exporting to JSON: {str(e)}")
        return False


def export_to_csv(events, output_file):
    """
    Export events to a CSV file

    Args:
        events: List of event dictionaries
        output_file: Path to the output CSV file

    Returns:
        True if successful, False otherwise
    """
    try:
        # Create output directory if it doesn't exist
        os.makedirs(os.path.dirname(output_file), exist_ok=True)

        # Define CSV fields
        fieldnames = [
            'id', 'type', 'start_time', 'end_time', 'duration',
            'confidence', 'video_path', 'output_file'
        ]

        # Write to CSV file
        with open(output_file, 'w', newline='', encoding='utf-8') as f:
            writer = csv.DictWriter(f, fieldnames=fieldnames)
            writer.writeheader()

            for event in events:
                # Create a clean copy of the event for export
                export_event = {
                    'id': event.get('id'),
                    'type': event.get('type', ''),
                    'start_time': event.get('start_time', 0),
                    'end_time': event.get('end_time', 0),
                    'duration': event.get('duration', 0),
                    'confidence': event.get('confidence', 0),
                    'video_path': event.get('video_path', ''),
                    'output_file': event.get('output_file', '')
                }

                writer.writerow(export_event)

        logger.info(f"Exported {len(events)} events to {output_file}")
        return True

    except Exception as e:
        logger.error(f"Error exporting to CSV: {str(e)}")
        return False


def export_to_edit_decision_list(events, output_file):
    """
    Export events to an Edit Decision List (EDL) file

    Args:
        events: List of event dictionaries
        output_file: Path to the output EDL file

    Returns:
        True if successful, False otherwise
    """
    try:
        # Create output directory if it doesn't exist
        os.makedirs(os.path.dirname(output_file), exist_ok=True)

        # Write to EDL file
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write("TITLE: Football Event Cuts\n\n")

            for i, event in enumerate(events):
                event_num = i + 1
                video_path = os.path.basename(event.get('video_path', 'Unknown'))

                start_time = event.get('start_time', 0)
                end_time = event.get('end_time', 0)

                # Convert to timecode (HH:MM:SS:FF)
                # Assuming 30 fps for simplicity
                fps = 30

                def seconds_to_timecode(seconds):
                    h = int(seconds / 3600)
                    m = int((seconds % 3600) / 60)
                    s = int(seconds % 60)
                    f = int((seconds - int(seconds)) * fps)
                    return f"{h:02d}:{m:02d}:{s:02d}:{f:02d}"

                start_tc = seconds_to_timecode(start_time)
                end_tc = seconds_to_timecode(end_time)

                # Write EDL entry
                f.write(f"{event_num:03d}  {video_path}  V  C        ")
                f.write(f"{start_tc} {end_tc} ")
                f.write(f"{start_tc} {end_tc}\n")
                f.write(f"* {event.get('type', 'Unknown')} - Confidence: {event.get('confidence', 0):.2f}\n\n")

        logger.info(f"Exported {len(events)} events to EDL file {output_file}")
        return True

    except Exception as e:
        logger.error(f"Error exporting to EDL: {str(e)}")
        return False


def export_to_premiere_markers(events, output_file):
    """
    Export events to Adobe Premiere Pro markers XML

    Args:
        events: List of event dictionaries
        output_file: Path to the output XML file

    Returns:
        True if successful, False otherwise
    """
    try:
        # Create output directory if it doesn't exist
        os.makedirs(os.path.dirname(output_file), exist_ok=True)

        # Group events by video
        videos = {}

        for event in events:
            video_path = event.get('video_path', '')

            if video_path not in videos:
                videos[video_path] = []

            videos[video_path].append(event)

        # Create XML content
        xml_content = '<?xml version="1.0" encoding="UTF-8"?>\n'
        xml_content += '<xmeml version="4">\n'
        xml_content += '  <project>\n'
        xml_content += '    <name>Football Event Markers</name>\n'
        xml_content += '    <children>\n'

        # Add each video as a bin
        for video_path, video_events in videos.items():
            video_name = os.path.basename(video_path)

            xml_content += f'      <bin>\n'
            xml_content += f'        <name>{video_name}</name>\n'
            xml_content += f'        <children>\n'

            # Add the clip with markers
            xml_content += f'          <clip>\n'
            xml_content += f'            <name>{video_name}</name>\n'
            xml_content += f'            <duration>3600</duration>\n'  # Placeholder duration
            xml_content += f'            <rate>\n'
            xml_content += f'              <timebase>30</timebase>\n'  # Assuming 30fps
            xml_content += f'              <ntsc>TRUE</ntsc>\n'
            xml_content += f'            </rate>\n'

            # Add markers
            xml_content += f'            <markers>\n'

            for i, event in enumerate(video_events):
                start_time = event.get('start_time', 0)
                end_time = event.get('end_time', 0)

                # Convert to frames (assuming 30fps)
                start_frame = int(start_time * 30)

                xml_content += f'              <marker>\n'
                xml_content += f'                <name>{event.get("type", "Event")} {i + 1}</name>\n'
                xml_content += f'                <comment>Confidence: {event.get("confidence", 0):.2f}</comment>\n'
                xml_content += f'                <in>{start_frame}</in>\n'
                xml_content += f'                <out>{int(end_time * 30)}</out>\n'
                xml_content += f'              </marker>\n'

            xml_content += f'            </markers>\n'
            xml_content += f'          </clip>\n'
            xml_content += f'        </children>\n'
            xml_content += f'      </bin>\n'

        xml_content += '    </children>\n'
        xml_content += '  </project>\n'
        xml_content += '</xmeml>\n'

        # Write to file
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(xml_content)

        logger.info(f"Exported {len(events)} events to Premiere markers XML {output_file}")
        return True

    except Exception as e:
        logger.error(f"Error exporting to Premiere markers: {str(e)}")
        return False


def import_from_json(input_file):
    """
    Import events from a JSON file

    Args:
        input_file: Path to the input JSON file

    Returns:
        List of event dictionaries
    """
    try:
        if not os.path.exists(input_file):
            logger.error(f"Input file not found: {input_file}")
            return []

        # Read from JSON file
        with open(input_file, 'r', encoding='utf-8') as f:
            events = json.load(f)

        # Process imported events
        processed_events = []

        for event in events:
            # Format frames if frame_start and frame_end are available
            if 'frame_start' in event and 'frame_end' in event:
                event['frames'] = {
                    'start': event.pop('frame_start'),
                    'end': event.pop('frame_end')
                }

            processed_events.append(event)

        logger.info(f"Imported {len(processed_events)} events from {input_file}")
        return processed_events

    except Exception as e:
        logger.error(f"Error importing from JSON: {str(e)}")
        return []